const LikeClassifyModule = require('../../modules/recommend/likeClassify')
const qs = require('querystring')

class LikeClassifyControllers {
  /**
   * 设置偏好
   */
  static async setLikeClassify(ctx) {
    const req = ctx.request.body
    if (!req.userId) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    if (!req.classifyKey) {
      req.classifyKey = []
    }
    try {
      let like = await LikeClassifyModule.getLikeClassify({
        userId: req.userId
      })
      if (like) {
        await LikeClassifyModule.updateLikeClassify({
          userId: req.userId
        }, {
          classifyKey: JSON.stringify(req.classifyKey)
        })
      } else {
        await LikeClassifyModule.setLikeClassify({
          userId: req.userId,
          classifyKey: JSON.stringify(req.classifyKey)
        })
      }
      ctx.body = {
        code: 200,
        msg: 'success'
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }

  /**
   * 获取偏好
   */
  static async getLikeClassify(ctx) {
    let req = qs.parse(ctx.request.url.split('?')[1])
    if (!req.userId) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      let like = await LikeClassifyModule.getLikeClassify({
        userId: req.userId
      })
      console.log(like)
      like.classifyKey = like.classifyKey == '[]' ? [] : JSON.parse(like.classifyKey)
      ctx.body = {
        code: 200,
        data: like
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    } 
  }
}

module.exports = LikeClassifyControllers
